package com.example.wxjava.util;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/wechats")
public class WechatController {
    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;
    @Autowired
    private WxMpService wxMpService;
    private static final String TOKEN = "sadasdasdsadsasaasd";

    @GetMapping
    public String checkValid(String signature, String timestamp,
                             String nonce, String echostr) {
        return checkSignature(timestamp, nonce, signature) ? echostr
                : "校验失败";
    }

    /**
     * 校验 signature(签名) 的正确性
     * a. 将 token、timestamp、nonce 三个参数进行字典序排序
     * b. 将三个参数字符串拼接为一个字符串后进行 sha1 加密
     * c. 把 sha1 加密后的字符串与 signature 的值进行比较
     * d. 若相同, 返回 true; 若不相同, 返回 false
     */
    public boolean checkSignature(String timestamp, String nonce, String signature) {

        String[] params = {TOKEN, timestamp, nonce};
        Arrays.sort(params);

        // b. 将三个参数字符串拼接为一个字符串后进行 sha1 加密
        StringBuilder joinParam = new StringBuilder();
        for (String param : params) {
            joinParam.append(param);
        }

        String secretParam = DigestUtils.sha1Hex(joinParam.toString());

        return secretParam.equals(signature);
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String handleMessage(@RequestBody String requestBody,
                                @RequestParam("signature") String signature,
                                @RequestParam("timestamp") String timestamp,
                                @RequestParam("nonce") String nonce) {
        System.out.println("111");

        // 校验消息是否来自微信
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        // 解析消息体，封装为对象
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
        WxMpXmlOutMessage outMessage;
        try {
            // 将消息路由给对应的处理器，获取响应
            outMessage = wxMpMessageRouter.route(inMessage);
        } catch (Exception e) {
            outMessage = null;
        }
        // 将响应消息转换为xml格式返回
        return outMessage == null ? "" : outMessage.toXml();
    }



}

